import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {Button, Picker, Text, View} from '@tarojs/components'
import {
  AtDrawer,
  AtIcon,
  AtInput,
  AtList,
  AtListItem,
  AtModal,
  AtModalAction,
  AtModalContent,
  AtModalHeader,
  AtTextarea
} from "taro-ui";
import './manage-appointment.scss'
import {
  MY_SUPPLIER_IDENTITY,
  DO_DEAL,
  CHANGE_DATE,
  MY_SUPPLIER,
  IS_REFUSE
} from '../../constants/api'
import {vcmonitor} from "../../utils/tools";
import {newHttp} from "../../utils/request";
import {http} from "../../utils/http";
import {UserIdentity} from "../../utils/server.interface";
import {user} from "../../utils/user.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import Index from "../components/water-mark/index";

interface StateType {
  show: boolean
  isRefuseOpen: boolean
  isChangeDate: boolean
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  tabIndex: number
  queryData: {
    supplierId: string
    reserveDateEnd: string
    reserveDate: string
    reserveStatus: string
    link_phone: string
    link_name: string
    goods_name: string
    pageSize: number
    pageNumber: number
  }
  refuseData: object
  changeData: object
  supplierIndex: number
  supplierChecked: string
  listData: any
  tabData: any
  supplierList: any
}

export default class ManageAppointment extends Component {
  state: StateType = {
    tabData: [{title: '全部', index: 0, value: ''}, {title: '未安排', index: 1, value: '0'}, {title: '已安排', index: 2, value: '1'}],
    loadMoreStatus: 'loading',
    queryData: {
      supplierId: '',
      reserveDateEnd: '',
      reserveDate: '',
      reserveStatus: '',
      link_phone: '',
      link_name: '',
      goods_name: '',
      pageSize: 10,
      pageNumber: 1
    },
    changeData: {
      reserve_date: '',
      reserve_date_end: '',
      reserve_date_range: '',
      id: '',
      order_id: '',
      oldDate: '',
      supplier_id: '',
      appointment_day: ''
    },
    tabIndex: 0,
    supplierChecked: '',
    supplierIndex: 0,
    show: false,
    isRefuseOpen: false,
    isChangeDate: false,
    refuseData: {
      order_num: '',
      order_id: '',
      supplier_id: '',
      reason_for_refusal: ''
    },
    listData: [],
    supplierList: []
  }
  page = 1

  async componentDidShow() {
    vcmonitor(this)
  }

  async UNSAFE_componentWillMount() {
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/index/index'})
      }, 1500)
      return
    } else {
      const userIdentity = await http.get<UserIdentity>(MY_SUPPLIER_IDENTITY, {})
      if (userIdentity && userIdentity.supplierAuditorList) {
        let supplierChecked = ''
        const supplierIndex = 0
        if (userIdentity.supplierAuditorList.length > 0) {
          supplierChecked = userIdentity.supplierAuditorList[supplierIndex].company
          this.state.queryData.supplierId = userIdentity.supplierAuditorList[supplierIndex].supplier_id
        }
        this.setState({supplierList: userIdentity.supplierAuditorList, supplierChecked, supplierIndex})
      } else {
        Taro.showToast({
          title: '您还没有供应商，请确认用户身份',
          icon: 'none',
          mask: true
        })
        const timer = setTimeout(() => {
          clearTimeout(timer)
          Taro.switchTab({url: '/pages/index/index'})
        }, 1500)
        return
      }
    }
    this.getListData(this.state.queryData)
  }

  async onPullDownRefresh() {
    Taro.showNavigationBarLoading()
    const {queryData} = this.state
    this.page = 1
    queryData['pageNumber'] = this.page
    const data = await newHttp.get(MY_SUPPLIER, this.state.queryData)
    this.setState({queryData, listData: data.data.list})
    Taro.hideNavigationBarLoading()
    Taro.stopPullDownRefresh()
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const {queryData} = this.state
      this.page++
      queryData['pageNumber'] = this.page
      const old = this.state.listData
      const data = await newHttp.get(MY_SUPPLIER, queryData)
      if (data.isOk) {
        if (data.data.list.length < queryData.pageSize) {
          this.setState({loadMoreStatus: 'noMore'})
        } else {
          this.setState({loadMoreStatus: 'more'})
        }
        this.setState({queryData, listData: [...old, ...data.data.list]})
      }
    }
  }

  async getListData(queryData) {
    Taro.showLoading({title: '加载中'})
    const data = await newHttp.get(MY_SUPPLIER, queryData)
    if (data.isOk) {
      if (data.data.list.length < queryData.pageSize) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      this.setState({queryData, listData: data.data.list})
      Taro.hideLoading()
    } else {
      Taro.showToast({
        title: data.msg,
        icon: 'none',
      })
      Taro.hideLoading()
    }
    Taro.hideLoading()
  }

  handlerTab(tabIndex, reserveStatus) {
    const {queryData} = this.state
    this.page = 1
    queryData['pageNumber'] = this.page
    queryData['reserveStatus'] = reserveStatus
    this.setState({tabIndex, queryData})
    this.getListData(queryData)
  }

  handleChange(field, val) {
    if (typeof val === 'object') {
      val = val.detail.value
    }
    const {queryData} = this.state
    queryData[field] = val
    this.setState({queryData})
  }

  onClose() {
    this.setState({show: false})
  }

  handleForm(flag) {
    const {queryData} = this.state
    this.page = 1
    queryData['pageNumber'] = 1
    if (flag) {
      queryData['reserveDateEnd'] = ''
      queryData['reserveDate'] = ''
      queryData['link_phone'] = ''
      queryData['link_name'] = ''
      queryData['goods_name'] = ''
      this.setState({queryData})
      return
    }
    this.onClose()
    this.getListData(queryData)
  }

  onChange(e) {
    const {supplierList, queryData} = this.state
    this.page = 1
    queryData['pageNumber'] = 1
    const supplierIndex = Number(e.detail.value)
    queryData['supplierId'] = supplierList[supplierIndex].supplier_id
    const supplierChecked = supplierList[supplierIndex].company
    this.setState({supplierIndex, supplierChecked})
    Taro.setStorageSync('mySupplierIndex', supplierIndex)
    this.getListData(queryData)
  }

  refuseHandleChange(val) {
    const {refuseData} = this.state
    refuseData['reason_for_refusal'] = val
    this.setState({refuseData})
  }

  onDateChange(field, e) {
    const {changeData} = this.state
    changeData[field] = e.detail.value
    this.setState({changeData})
  }

  async confirmChangeDate() {
    const {changeData} = this.state
    if (changeData.appointment_day === 'more') {
      if (!changeData.reserve_date) {
        return Taro.showToast({title: '请选择开始日期', icon: 'none'})
      } else if (!changeData.reserve_date_end) {
        return Taro.showToast({title: '请选择结束日期', icon: 'none'})
      }
    } else {
      if (!changeData.reserve_date) {
        return Taro.showToast({title: '请选择日期', icon: 'none'})
      }
    }
    if (changeData.appointment_day === 'more') {
      changeData.reserve_date_range = changeData.reserve_date + ',' + changeData.reserve_date_end
    }
    const data = await newHttp.post(CHANGE_DATE, changeData)
    if (data.isOk) {
      const {queryData} = this.state
      this.page = 1
      queryData['pageNumber'] = 1
      this.getListData(queryData)
      Taro.showToast({title: '改期成功', icon: 'none'})
      this.setState({isChangeDate: false})
    } else {
      this.setState({isChangeDate: false})
      Taro.showToast({title: data.msg, icon: 'none'})
    }
  }

  async confirmRefuse() {
    const data = await newHttp.post(IS_REFUSE, this.state.refuseData)
    if (data.isOk) {
      const {queryData} = this.state
      this.page = 1
      queryData['pageNumber'] = 1
      this.getListData(queryData)
      Taro.showToast({title: '拒绝成功', icon: 'none'})
      this.setState({isRefuseOpen: false})
    } else {
      this.setState({isRefuseOpen: false})
      Taro.showToast({title: data.msg, icon: 'none'})
    }
  }

  closedWithDraw() {
    this.setState({isRefuseOpen: false})
  }

  async doDeal(Id, order_id) {
    const data = await newHttp.post(DO_DEAL, {Id, order_id})
    if (data.isOk) {
      const {queryData} = this.state
      this.getListData(queryData)
      Taro.showToast({title: '安排成功', icon: 'none'})
    } else {
      Taro.showToast({title: '操作失败', icon: 'none'})
    }
  }

  doRefuse(order_num, order_id) {
    const refuseData = {order_num, order_id, reason_for_refusal: '', supplier_id: this.state.queryData.supplierId}
    this.setState({isRefuseOpen: true, refuseData})
  }

  doChangeDate(id, order_id, appointment_day, oldDate) {
    const changeData = {id, order_id, appointment_day, oldDate, supplier_id: this.state.queryData.supplierId}
    this.setState({isChangeDate: true, changeData})
  }

  render() {
    const {tabData, changeData, isRefuseOpen, isChangeDate, refuseData, supplierList, supplierChecked, supplierIndex, listData, tabIndex, show, queryData, loadMoreStatus} = this.state
    return (
      <View className='root yuyue-root'>
        <GzhAuth />
        <Index />
        <View className='header-top'>
          <View className='head-picker'>
            {supplierList.length > 1 &&
            <Picker value={supplierIndex} range={supplierList} rangeKey='company' onChange={this.onChange.bind(this)}>
              <View className={supplierChecked ? 'picker' : 'picker off'}>
                {supplierChecked ? '供应商: ' + supplierChecked : '请先选择供应商'}
                <Text>切换</Text>
              </View>
            </Picker>}
          </View>
        </View>
        <View className='tab-header'>
          {tabData && tabData.map(item =>
            <View key={item.index} className={`tab-item ${tabIndex === item.index ? 'tab-item-active' : ''}`}
              onClick={this.handlerTab.bind(this, item.index, item.value)}
            >
              <View className='line-title'>
                {item.title}
              </View>
              <View className={`at-tabs_item_underline ${tabIndex === item.index ? 'underline-active' : ''}`} />
            </View>
          )}
          <View className='tab-item-search-supplier' onClick={() => {
            this.setState({show: true})
          }}
          >筛选<AtIcon prefixClass='car' size='16' value='iconshaixuan' color='#f0d4a8'></AtIcon></View>
        </View>
        <AtDrawer show={show} right mask onClose={this.onClose.bind(this)}>
          <View className='view-m-b'>
            <AtInput clear name='goods_name' title='商品名称' type='text' value={queryData.goods_name}
              onChange={this.handleChange.bind(this, 'goods_name')}
            />
          </View>
          <View className='view-m-b'>
            <AtInput clear name='link_name' title='客户姓名' type='text' value={queryData.link_name}
              onChange={this.handleChange.bind(this, 'link_name')}
            />
          </View>
          <View className='link_phone_box'>
            <AtInput clear name='link_phone' className='link_phone' title='客户电话' type='phone'
              value={queryData.link_phone} onChange={this.handleChange.bind(this, 'link_phone')}
            />
          </View>
          <View className='view-m-b-reserve-date'>
            <Picker mode='date' onChange={this.handleChange.bind(this, 'reserveDate')}>
              <AtList>
                <AtListItem title='预订时间起' extraText={queryData.reserveDate} />
              </AtList>
            </Picker>
          </View>
          <View className='view-m-b view-m-b-reserve-date-end'>
            <Picker mode='date' onChange={this.handleChange.bind(this, 'reserveDateEnd')}>
              <AtList>
                <AtListItem title='预订时间止' extraText={queryData.reserveDateEnd} />
              </AtList>
            </Picker>
          </View>
          <View className='dialog-footer'>
            <View className='reset' onClick={this.handleForm.bind(this, true)}>重置</View>
            <View className='search' onClick={this.handleForm.bind(this, false)}>搜索</View>
          </View>
        </AtDrawer>
        {listData && listData.length > 0 &&
        <View className='article-body'>
          {listData.map((item, index) =>
            <View className='article-item' key={item.DT_RowId}>
              <View className='article-body-header'>
                <View className='header-left'>{item.appointmentName}</View>
                <View className='header-right'>{item.statusStr}</View>
              </View>
              <View className='line' />
              <View className='goods-item'>商品名称：{item.goodsName}</View>
              <View className='goods-item'>客户姓名：{item.linkman}</View>
              <View className='goods-item'>客户电话：{item.phone}</View>
              <View className='goods-item'>预约日期：{item.add_date}</View>
              <View className='goods-item'>预订日期：{item.reserve_date}</View>
              {item.change_date_remark && <View className='goods-item'>改期日期：<Text
                className='change-date'
              >{item.change_date_remark.reserve_date}</Text></View>}
              <View className='goods-item'>预约数量：{item.num}</View>
              <View className='btnGroup'>
                {item.isDoDeal &&
                <View className='arrangement' onClick={this.doDeal.bind(this, item.DT_RowId, item.order_id)}>
                  <View className='arrangement-btn'>安排</View>
                </View>}
                {item.isRefuse &&
                <View className='arrangement' onClick={this.doRefuse.bind(this, item.order_num, item.order_id)}>
                  <View className='arrangement-btn'>拒绝</View>
                </View>}
                {item.isChangeDate &&
                <View className='arrangement'
                  onClick={this.doChangeDate.bind(this, item.DT_RowId, item.order_id, item.appointment_day, item.appointment_day === 'more' ? item.reserve_date : item.reserve_date_end)}
                >
                  <View className='arrangement-btn'>改期</View>
                </View>}
              </View>
              {isRefuseOpen && <AtModal isOpened={isRefuseOpen} className='manage-appointment' onClose={this.closedWithDraw.bind(this)}>
                <AtModalHeader>拒绝</AtModalHeader>
                <AtModalContent>
                  <AtTextarea
                    count={false}
                    value={refuseData.reason_for_refusal}
                    onChange={this.refuseHandleChange.bind(this)}
                    maxLength={200}
                    placeholder='拒绝原因'
                  />
                </AtModalContent>
                <AtModalAction> <Button onClick={() => {
                  this.setState({isRefuseOpen: false})
                }}
                >取消</Button> <Button onClick={this.confirmRefuse.bind(this)}>确定</Button> </AtModalAction>
              </AtModal>}
              <AtModal isOpened={isChangeDate} className='manage-appointment'>
                <AtModalHeader>改期</AtModalHeader>
                <AtModalContent>
                  {changeData.appointment_day !== 'more' && <View>
                    <Text className='text-cla'>原到期时间：{changeData.oldDate}</Text>
                    <Text className='text-cla expire-date'>更改到期时间：</Text>
                    <Picker mode='date' onChange={this.onDateChange.bind(this, 'reserve_date')}>
                      <AtList>
                        <AtListItem title='请选择日期' extraText={changeData.reserve_date} />
                      </AtList>
                    </Picker>
                  </View>}
                  {changeData.appointment_day === 'more' && <View>
                    <Text className='text-cla'>原到期时间：{changeData.oldDate}</Text>
                    <Text className='text-cla expire-date'>更改到期时间：</Text>
                    <Picker className='start-date' mode='date' onChange={this.onDateChange.bind(this, 'reserve_date')}>
                      <AtList>
                        <AtListItem title='开始日期：' extraText={changeData.reserve_date} />
                      </AtList>
                    </Picker>
                    <Picker mode='date' onChange={this.onDateChange.bind(this, 'reserve_date_end')}>
                      <AtList>
                        <AtListItem title='结束日期：' extraText={changeData.reserve_date_end} />
                      </AtList>
                    </Picker>
                  </View>}
                </AtModalContent>
                <AtModalAction> <Button onClick={() => {
                  this.setState({isChangeDate: false})
                }}
                >取消</Button> <Button onClick={this.confirmChangeDate.bind(this)}>确定</Button> </AtModalAction>
              </AtModal>
            </View>
          )}
        </View>}
      </View>
    )
  }
}
